package com.stronger.common.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Created by njy on 2023/7/5
 */
@Configuration
public class ExecutorConfig {

    // 核心线程数
    private int corePoolSize = 5;
    // 最大线程数
    private int maxPoolSize = 10;
    // 队列大小
    private int queueSize = 100;
    // 线程最大空闲时间
    private int keepAliveSeconds = 100;
    /**
     * CallerRunsPolicy 这个策略重试添加当前的任务，他会自动重复调用 execute() 方法，直到成功。
     * AbortPolicy 对拒绝任务抛弃处理，并且抛出异常。
     * DiscardPolicy 对拒绝任务直接无声抛弃，没有异常信息。
     * DiscardOldestPolicy 对拒绝任务不抛弃，而是抛弃队列里面等待最久的一个线程，然后把拒绝任务加到队列。
     * @return
     */
    @Bean(value = "testThreadPool")
    public ThreadPoolTaskExecutor buildFirstThreadPool() {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(corePoolSize);
        threadPool.setMaxPoolSize(maxPoolSize);
        threadPool.setQueueCapacity(queueSize);
        threadPool.setThreadNamePrefix("testThreadPool-");
        threadPool.setKeepAliveSeconds(keepAliveSeconds);
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //如果@Bean 就不需手动，会自动InitializingBean的afterPropertiesSet来调initialize
//      threadPool.initialize();
        return threadPool;
    }


}
